﻿@implements IDisposable
@inject DemoConfiguration Configuration
@inject NavigationManager NavigationManager

<DemoScriptLoader @ref=@navPanelHelper Src="_content/BlazorDemo/lib/page-nav.js">
</DemoScriptLoader>

<div class="demo-page-nav @(!visible ? "d-none" : "")">
    @if(visible) { 
        <DemoPageNavHeader Title="@demoPageSections.First().Title" @bind-StateCssClass="@HeaderCssClass"></DemoPageNavHeader>
        <div class="nav-pills">
            <div class="nav-title">@demoPage.Title</div>
            @foreach(var(demoPageSection, i) in demoPageSections.Select((s, index) => (s, index))) {
                <DemoPageNavPanelItem @key="@($"{demoPage.Url}|{i}")"
                                      Text="@demoPageSection.Title"
                                      Url="@($"{demoPage.Url}#{demoPageSection.Id}")"
                                      CssClass="@GetItemCssClass(i)">
                    <Badge>@GetBadgeText(demoPageSection)</Badge>
                </DemoPageNavPanelItem>
            }
        </div>
    }
</div>

@code {
    DemoScriptLoader navPanelHelper;

    IEnumerable<DemoPageSection> demoPageSections;
    DemoPage demoPage;

    bool visible;

    public string HeaderCssClass { get; set; } = "collapse";

    protected override void OnInitialized() {
        NavigationManager.LocationChanged += OnLocationChanged;
        UpdateVisibility(NavigationManager.Uri);
    }

    protected override async Task OnAfterRenderAsync(bool firstRender) {
        await navPanelHelper.InvokeVoidAsync("DemoPageNavPanel.addDemoAnchorIntersectionObserver");
    }

    string GetItemCssClass(int itemIndex) {
        if(itemIndex == 0) {
            var uriFragment = NavigationManager.ToAbsoluteUri(NavigationManager.Uri).Fragment.Replace("#", "");
            if(string.IsNullOrEmpty(uriFragment))
                return "nav-target";
        }
        return "";
    }

    string GetBadgeText(DemoPageSection demoPageSection) {
        if(demoPageSection.IsNew)
            return "New";
        if(demoPageSection.IsUpdated)
            return "Upd";
        return null;
    }

    void OnLocationChanged(object sender, LocationChangedEventArgs args) {
        HeaderCssClass = "collapse";
        UpdateVisibility(args.Location);
        InvokeAsync(StateHasChanged);
    }

    void UpdateVisibility(string currentUri) {
        var demoPageUrl = NavigationManager.ToAbsoluteUri(currentUri).GetLeftPart(UriPartial.Path).Replace(NavigationManager.BaseUri, "");
        if(demoPageUrl.EndsWith('/'))
            demoPageUrl = demoPageUrl.Substring(0, demoPageUrl.LastIndexOf('/'));
        demoPageSections = Configuration.GetDemoPageSections(demoPageUrl, out demoPage);
        visible = demoPageSections.Any();
    }

    public void Dispose() {
        NavigationManager.LocationChanged -= OnLocationChanged;
    }
}
